package com.cd.sendRequest;

import com.cd.common.constant.Constants;
import com.cd.common.util.AuthUtils;
import com.cd.sendRequest.controller.SendController;
import com.cd.sendRequest.entity.CurlParser;
import com.cd.sendRequest.entity.CurlRequest;
import com.cd.sendRequest.jpa.domain.CURLStore;
import com.cd.sendRequest.jpa.domain.CookieStore;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class GenericCurlExecutor {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GenericCurlExecutor.class);

    public static void main(String[] args) {
        String curlCommand = "curl 'http://47.116.126.63:10290/lqq/card/draw?pageNum=1&pageSize=10&num=10&mode=0' \n" +
                "  -H 'Accept: application/json, text/plain, */*' \n" +
                "  -H 'Accept-Language: zh-CN,zh;q=0.9' \n" +
                "  -H 'Authorization: LqqToken eyJhbGciOiJIUzI1NiJ9...' \n" +
                "  -b 'rememberMe=true; username=admin; password=nYI0p63uZG0OcqSPazu3tVRAY0M5TWk2N9t7LZMUltjPsaBu72CH2vcGtDzhNe8uB2dcjbosXZpErte2CqYaVg==; Admin-Token=eyJhbGciOiJIUzI1NiJ9...' \n" +
                "  -H 'Referer: http://47.116.126.63:10290/card/draw' \n" +
                "  -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \n" +
                "  --insecure";
        send(curlCommand,1);
    }

    public static void send(String curlCommand,int count) {
        // 示例 curl 命令
//        curlCommand = "curl 'http://47.116.126.63:10290/lqq/card/draw?pageNum=1&pageSize=10&num=10&mode=0' \n" +
//                "  -H 'Accept: application/json, text/plain, */*' \n" +
//                "  -H 'Accept-Language: zh-CN,zh;q=0.9' \n" +
//                "  -H 'Authorization: LqqToken eyJhbGciOiJIUzI1NiJ9...' \n" +
//                "  -b 'rememberMe=true; username=admin; password=nYI0p63uZG0OcqSPazu3tVRAY0M5TWk2N9t7LZMUltjPsaBu72CH2vcGtDzhNe8uB2dcjbosXZpErte2CqYaVg==; Admin-Token=eyJhbGciOiJIUzI1NiJ9...' \n" +
//                "  -H 'Referer: http://47.116.126.63:10290/card/draw' \n" +
//                "  -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36' \n" +
//                "  --insecure";

        CurlParser parser = new CurlParser();
        CurlRequest request = parser.parse(curlCommand);

        //ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 每隔 1 秒执行一次请求

        //int count = 10; // 发送请求的次数
        for (int i = 0; i < count; i++) {
            try {
                sendRequest(request); // 发送请求
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            logger.info("已发送请求次数：" + (i + 1));
            try {
                Thread.sleep(1000); // 等待一秒
            } catch (InterruptedException e) {
                logger.error("线程被中断", e);
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }
        logger.info("已完成{}次请求", count);
    }


    //计划用于批量拉取粉丝数据

    private static void sendRequest(CurlRequest request) throws Exception {
        URL url = new URL(request.getUrl());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // ✅ 设置请求方法
        conn.setRequestMethod("POST");

        // ✅ 允许重定向（等价于 curl --location）
        conn.setInstanceFollowRedirects(true);

        // ✅ 添加 Headers（完全复制 curl）
        for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
            if (!entry.getKey().equals("Content-Length")) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        // ✅ Cookie（确保完整）
        Long userId = AuthUtils.currentUserId();
        // ✅ 启用 gzip（curl 默认支持，我们也支持）
        //conn.setRequestProperty("Accept-Encoding", "gzip");

        //写入请求体
        conn.setDoOutput(true);
        if (request.getBody()!=null && request.getBody().length()>0) {
            byte[] input = request.getBody().getBytes(StandardCharsets.UTF_8);
            conn.getOutputStream().write(input, 0, input.length);
        }

        // ✅ 连接
        conn.connect();

        // ✅ 获取响应码
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // ✅ 判断输入流来源
        InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ?
                conn.getInputStream() : conn.getErrorStream();

        // ✅ 检查是否是 gzip 压缩
        String contentEncoding = conn.getContentEncoding();
        if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
            inputStream = new GZIPInputStream(inputStream);
        }

        // ✅ 使用 UTF-8 读取文本
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8)
        );

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line).append("\n");
        }
        reader.close();
        inputStream.close();
        conn.disconnect();
        logger.info("返回报文为=>[{}]", response.toString());
    }
}